<?php
/**
 * Created by PhpStorm.
 * User: asus
 * Time: 15:34
 */
namespace app\index\business;
use app\index\business\BaseBusiness;
use app\index\model\UserCollectType;
use app\libs\Functions;
use app\libs\SendSms;
use think\Config;
use app\index\model\UserModel;
use think\Db;
use think\exception\PDOException;
use think\Request;
use think\Route;

class User extends BaseBusiness
{
    const user_key = 'qc:string:ischeckcode:phone:';

    public function register($data)
    {
        //判断手机号是否存在
       $phone = UserModel::getUserByPhone($data['phone'],'id');
       if ($phone){
           $this->result['status'] = -1;
           $this->result['msg'] = '该手机号已经被注册';
           return $this->result;
       }

        //验证手机验证码是否正确（true：正确 false：失败 2：输入次数过多)
        $userFlag = $this->getBusiness('Mobile')->checkPhoneCode($data['phone'],$data['captcha'],Config::get('mobile_code.register'));

       if (!$userFlag){
            $this->result['status'] = -1;
            $this->result['msg'] = '手机验证码不正确';
            return $this->result;
        }

        if ($userFlag === 2){
            $this->result['status'] = -1;
            $this->result['msg'] = '手机验证码输入错误次数太多，请稍后再试';
            return $this->result;
        }
        //入库
        $user_no = Functions::numCodeNoRe(18);
        $userData['user_no'] = $user_no;
        $userData['username'] = Functions::rand_cn_name();
        $userData['phone'] = $data['phone'];
        $userData['password_salt'] = Functions::uniqueString('64');
        $userData['password'] = Functions::encryptPassword($data['password'],$userData['password_salt'] );
        $userData['status'] = 1;
        $userData['is_auth'] = 0;
        $userData['rolo_id'] = -1;
        $userData['admin_id'] = 20;
        $userData['chains'] = $data['chains'];
        $userData['vip'] = 0;
        $userData['created_at'] = $userData['updated_at'] = $userData['lastlogin_at'] = time();

        // 启动事务
        Db::startTrans();
        try {
            /***如果有openid就是修改没有就插入**/
            if (empty($data['openid'])){
                // 新加一条用户信息
                UserModel::create($userData);
            }else{
                db('user')->where('openid',$data['openid'])->update($userData);
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->result['status'] = -1;
            $this->result['msg'] = '用户注册信息录入失败';
            return $this->result;
        }
        //删除缓存中的手机验证码
        $this->getBusiness('Mobile')->delSms(Config::get('mobile_code.register'),$data['phone']);
        $afterLoginToken = $this->userAfterLogin($userData);
        if (!$afterLoginToken){
            $this->result['status'] = -1;
            $this->result['msg'] = 'token生成失败';
            return $this->result;
        }

        //整理输出数据
        $afterLoginToken['phone'] = $userData['phone'];
        $afterLoginToken['username'] = $userData['username'];
        $afterLoginToken['vip'] = 0;
        $this->result['status'] = 1;
        $this->result['msg'] = '注册登录成功';
        $this->result['data'] = $afterLoginToken;
        return $this->result;
    }

    /**
     * @param $userData
     * 登录注册中间方法
     */
    public function userAfterLogin($userData){
        if(!$userData ){
            $this->result['status'] = -1;
            $this->result['msg'] = '登录失败';
            return $this->result;
        }
        // 生成token
        $tokenData['login_status'] = 1;
        $tokenData['user_no'] = $userData['user_no'];
        $token['tokenPassword'] = Functions::uniqueString(16);
        $token['token'] = $this->getBusiness('RedisCache')->createToken($tokenData,$token['tokenPassword']);

        header('token:' . base64_encode($token['token']));
        header('tokenpassword:' . $token['tokenPassword']);

        //存redis
        $redisData['login_status'] = $tokenData['login_status'];
        $redisData['api_refresh_time'] = time();
        $redisData['paypassword'] = $userData['password'];
        $redisData['password_salt'] = $userData['password_salt'];
        $redisData['phone'] = $userData['phone'];
        $redisData['user_no'] = $userData['user_no'];
        $redisData['username'] = $userData['username'];
        $redisData['status'] = $userData['status'];
        $redisData['is_auth'] = $userData['is_auth'];
        $redisData['token'] = $token['token'];
        $redisData['tokenPassword'] = $token['tokenPassword'];

        $saveRedis = $this->getBusiness('RedisCache')->userCache($userData['user_no'], $token['tokenPassword'], $redisData);
        // 记录用户最近一次登录的时间
        Db::table('cq_user')->where('user_no',$userData['user_no'])->update(['lastlogin_at'=>time()]);

        $token = base64_encode($token['token']);
        $tokenPassword = $redisData['tokenPassword'];
        $returnData = compact('token','tokenPassword');
        return $returnData;
    }

    public function login($phone,$password,$captcha,$login_type,$code){
        // 验证用户是否存在
        $feild = 'id,user_no,phone,username,password,password_salt,status,is_auth,rolo_id,vip,openid';
        $user = $this->getModel('userModel')->getUserByPhone($phone,$feild);
        if (!$user){
            $this->result['status'] = -1;
            $this->result['msg'] = '用户不存在';
            return $this->result;
        }
        // 用户是否被禁用
        if ($user == 2){
            $this->result['status'] = -1;
            $this->result['msg'] = '此账号已被禁用';
            return $this->result;
        }

        //验证手机验证码是否正确（true：正确 false：失败 2：输入次数过多） 验证码登录的用户
        if ($login_type === 2){
            $userFlag = $this->getBusiness('Mobile')->checkPhoneCode($phone,$captcha,Config::get('mobile_code.login'));

            if (!$userFlag){
                $this->result['status'] = -1;
                $this->result['msg'] = '手机验证码不正确';
                return $this->result;
            }

            if ($userFlag === 2){
                $this->result['status'] = -1;
                $this->result['msg'] = '手机验证码输入错误次数太多，请稍后再试';
                return $this->result;
            }
        }

        // 密码登录的用户
        if ($login_type == 1){
            //比对用户秘钥
            $encyptPwd = Functions::encryptPassword($password, $user['password_salt']);
            if ($encyptPwd != $user['password']) {
                $this->result['status'] = -1;
                $this->result['msg'] = '登录失败，用户或密码错误';
                return $this->result;
            }
        }

        //移动端微信登录进来的用户
        if (!empty($code)){
            if (empty($user['openid'])){
                /**用户第一次用微信授权登录**/
                $wx=new \app\index\controller\Wx();
                $wx_data=$wx->wx_get_openid($code);
                $userinfo=$wx->get_userinfo($wx_data['access_token'],$wx_data['openid']);
                $upd['openid']=$userinfo['openid'];
                $upd['nickname']=$userinfo['nickname'];
                $upd['avatar']=$userinfo['headimgurl'];
                $upd['sex']=$userinfo['sex'];
                $upd['updated_at']=time();
                db('user')->where(['user_no'=>$user['user_no'],'status'=>1])->update($upd);
            }
        }

        //删除手机验证码
        $this->getBusiness('Mobile')->delSms(Config::get('mobile_code.login'),$phone);
        // 生成token
        $afterLoginToken = $this->userAfterLogin($user);
        if (!$afterLoginToken){
            $this->result['status'] = -1;
            $this->result['msg'] = '登录失败';
            return $this->result;
        }

        //整理输出数据
        $afterLoginToken['phone'] = $phone;
        $afterLoginToken['username'] = $user['username'];
        $afterLoginToken['vip'] = $user['vip'];
        $this->result['status'] = 1;
        $this->result['msg'] = '登录成功';
        $this->result['data'] = $afterLoginToken;
        return $this->result;
    }

    // 验证密码第一步
    public function setpassword($phone,$captcha)
    {
        // 验证用户是否存在
        $feild = 'id,phone';
        $user = $this->getModel('userModel')->getUserByPhone($phone,$feild);
        if (!$user){
            $this->result['status'] = -1;
            $this->result['msg'] = '用户不存在';
            return $this->result;
        }
        // 用户是否被禁用
        if ($user == 2){
            $this->result['status'] = -1;
            $this->result['msg'] = '此账号已被禁用';
            return $this->result;
        }

        //验证手机验证码是否正确（true：正确 false：失败 2：输入次数过多） 验证码登录的用户
        $userFlag = $this->getBusiness('Mobile')->checkPhoneCode($phone, $captcha, Config::get('mobile_code.setpassword'));
        if (!$userFlag) {
            $this->result['status'] = -1;
            $this->result['msg'] = '手机验证码不正确';
            return $this->result;
        }

        if ($userFlag === 2) {
            $this->result['status'] = -1;
            $this->result['msg'] = '手机验证码输入错误次数太多，请稍后再试';
            return $this->result;
        }
        // 此时用户手机验证码 已经通过校验
        $this->redis->set(self::user_key .$phone,$captcha);
        $this->result['status'] = 1;
        $this->result['msg'] = '信息提交成功';
        return $this->result;
    }

    // 验证密码第二部
    public function newpassword($phone,$password)
    {
        // 判断用户验证码是否通过校验
        $captcha = $this->redis->get(self::user_key . $phone);
        if (!$captcha){
            return $this->error('请先完成第一步');
        }

        // 验证用户是否存在
        $feild = 'id,phone';
        $user = $this->getModel('userModel')->getUserByPhone($phone,$feild);
        if (!$user){
            $this->result['status'] = -1;
            $this->result['msg'] = '用户不存在';
            return $this->result;
        }
        // 用户是否被禁用
        if ($user == 2){
            $this->result['status'] = -1;
            $this->result['msg'] = '此账号已被禁用';
            return $this->result;
        }

        // 生成新的密码
        $newPassword = Functions::encryptPassword($password,$user['password_salt'] );

        // 启动事务 update
        Db::startTrans();
        try {
            //update一条用户信息
            UserModel::update(['id' => $user['id'],'password' => $newPassword]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->result['status'] = -1;
            $this->result['msg'] = '修改密码失败';
            return $this->result;
        }
        //删除缓存中的手机验证码
        $this->getBusiness('Mobile')->delSms(Config::get('mobile_code.setpassword'),$phone);

        $this->result['status'] = 1;
        $this->result['msg'] = '密码修改成功';
        return $this->result;
    }

    /**
     * 收藏行为
     * @param $identification
     * @param $type
     * @param $uuid
     * @return array
     */
    public function collectBehavior($identification ,$type,$uuid)
    {
        //选择表名
        $tbl = UserCollectType::$tableName .= $type;
        $model = new UserCollectType();
        $res = $model->table($tbl)
            ->where('user_no',$uuid)
            ->where('identification',$identification)
            ->where('status',1)
            ->column('id');

        if ($res){
            return $this->error('您已经收藏过了');
        }
        $insert = array('user_no' =>$uuid,'identification' =>$identification,'status' =>1,'created_at'=>time(),'updated_at' =>time());
        switch ($type) {
            case "_news":
                $url = Config::get('cloude.url') . Config::get('cloude.Industry')['industrydetail'];
                $curl_arr = $this->getBusiness('Common')->_curl_request_data($url, 'GET', array('identification' => $identification));
                if (!$curl_arr) {
                    $local_new=db('publish_news')->where(['status'=>1,'identification'=>$identification])->find();
                    if (empty($local_new)){
                        return $this->error('网络错误');
                    }
                    $insert['title'] = $local_new['news_name'];
                    $insert['desc'] = empty($local_new['desc']) ? '' : $local_new['desc'];
                    $insert['thumb'] = $local_new['image'];
                    $insert['colleted_at'] = $local_new['created_at'];
                }else{
                    $insert['title'] = $curl_arr['news_name'];
                    $insert['desc'] = empty($curl_arr['desc']) ? '' : $curl_arr['desc'];
                    $insert['thumb'] = $curl_arr['thumb'];
                    $insert['colleted_at'] = $curl_arr['create_time'];
                }
                break;
            case "_company":
                $url = Config::get('cloude.url') .Config::get('cloude.Company')['companydetail'];
                $curl_arr = $this->getBusiness('Common')->_curl_request_data($url, 'GET',array('identification' => $identification));
                if (!$curl_arr){
                    return $this->error('网络错误');
                }
                $insert['company_name'] = $curl_arr['company_name'];
                $insert['industry'] = $curl_arr['business']['industry'];
                $insert['city'] =empty($curl_arr['city']) ? '' :$curl_arr['city'][1]['name'];
                break;
            case "_tank_organ":
                $url = Config::get('cloude.url') .Config::get('cloude.Company')['companydetail'];
                $curl_arr = $this->getBusiness('Common')->_curl_request_data($url, 'GET', array('identification' => $identification,'tank_id'=>1));
                if (!$curl_arr) {
                    return $this->error('网络错误');
                }
                $insert['company_name'] = $curl_arr['company_name'];
                $insert['industry'] = $curl_arr['business']['industry'];
                $city=unserialize(Db::connect(Config::get('db_yd'))->table('yd_companys')->where(['status'=>1,'identification'=>$identification])->value('city_str'));
                if (isset($city)){
                    $city=isset($city[2]['name']) ? $city[2]['name'] :$city[1]['name'];
                }
                $insert['city'] =$city;
                break;
            case "_master":
                $url = Config::get('cloude.url') .Config::get('cloude.Invest')['tankdetail'];
                $curl_arr = $this->getBusiness('Common')->_curl_request_data($url, 'GET', array('identification' => $identification));
                if (!$curl_arr) {
                    return $this->error('网络错误');
                }
                $insert['name'] = $curl_arr['member_name'];
                $insert['desc'] = $curl_arr['desc'];
                $insert['thumb'] = $curl_arr['headimgurl'];
                break;
            case "_invest_organ":
                $url = Config::get('cloude.url') .Config::get('cloude.Invest')['investdetail'];
                $curl_arr = $this->getBusiness('Common')->_curl_request_data($url, 'GET', array('identification' => $identification,'act'=>'organ'));
                if (!$curl_arr) {
                    return $this->error('网络错误');
                }
                $insert['organ_name'] = $curl_arr['organ_name'];
                $insert['turns'] = $curl_arr['turns'];
                $insert['invest_time'] = $curl_arr['ty_invest_nums'];
                $insert['invest_money'] = $curl_arr['invest_nums'];
                $insert['industry'] = json_encode($curl_arr['industry']);
                $insert['city'] = json_encode($curl_arr['city']);
                break;
            case "_invest_event":
                $url = Config::get('cloude.url') .Config::get('cloude.Invest')['investdetail'];
                $curl_arr = $this->getBusiness('Common')->_curl_request_data($url, 'GET', array('identification' => $identification,'act'=>'event'));
                if (!$curl_arr) {
                    return $this->error('网络错误');
                }
                $insert['event_name'] = $curl_arr['event_name'];
                $insert['turns'] = $curl_arr['turns'];
                $insert['invest_time'] = $curl_arr['invest_time'];
                $insert['invest_money'] = $curl_arr['invest_money'];
                $insert['organ_name'] = empty($curl_arr['company_name']) ? '' : $curl_arr['company_name'];
                $insert['industry'] = json_encode($curl_arr['industry']);
                break;
            case "_project":
                $project = Db::table('cq_push_project')->where('identification',$identification)->where('status',1)->find();
                $insert['project_name'] = $project['company_name'];
                $insert['industry'] = empty($project['industry']) ? '' : implode('@',array_column(unserialize($project['industry']),'name'));
                $insert['city'] = empty($project['city']) ? '' : implode('@',array_column(unserialize($project['city']),'name'));
                break;
            case "_park";
                $url = Config::get('cloude.url') .Config::get('cloude.Park')['parkdetail'];
                $curl_arr = $this->getBusiness('Common')->_curl_request_data($url, 'GET', array('identification' => $identification));
                if (!$curl_arr) {
                    return $this->error('网络错误');
                }
                $insert['park_name']=$curl_arr['park_name'];
                $insert['logo']=$curl_arr['thumb'];
                $insert['city']=$curl_arr['province'].','.$curl_arr['p_city'];
                $insert['park_area']=$curl_arr['park_area'];
                $insert['score']=empty($curl_arr['score']) ? 0 : $curl_arr['score'];
                $insert['level']=$curl_arr['level'];
                break;
            default:
                return $this->error('未知类型');
        }
        Db::startTrans();
        try {
            //insert
            $model->table($tbl)->insert($insert);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            var_dump($e->getMessage());
            Db::rollback();
            $this->result['status'] = -1;
            $this->result['msg'] = '收藏失败';
            return $this->result;
        }
//        // 添加redis hashTable计数器
//        $count = (int)$this->redis->hget(Config::get('collect.count').$uuid,array_search($type,Config::get('collect')));
//        $this->redis->hset(Config::get('collect.count').$uuid,array_search($type,Config::get('collect')),bcadd($count,1));

        $this->result['status'] = 1;
        $this->result['msg'] = '收藏成功';
        return $this->result;
    }

    /**
     * 取消收藏
     * @param $identification
     * @param $type
     * @param $uuid
     * @return array
     */
    public function cancelCollection($identification ,$type,$uuid)
    {
        //选择表名
        $tbl = UserCollectType::$tableName .= $type;
        $model = new UserCollectType();
        $collect_val = $model->table($tbl)
            ->where('user_no',$uuid)
            ->where('identification',$identification)
            ->where('status',1)
            ->column('id');

        if (!$collect_val){
            return $this->error('你本来就没收藏过该品类');
        }

        Db::startTrans();
        try {
            $model->table($tbl)->where('id',$collect_val[0])->update(['status'=>2,'updated_at' =>time()]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            var_dump($e->getMessage());
            Db::rollback();
            $this->result['status'] = -1;
            $this->result['msg'] = '取消收藏失败';
            return $this->result;
        }
        // 添加redis hashTable计数器
//        $count = (int)$this->redis->hget(Config::get('collect.count').$uuid,array_search($type,Config::get('collect')));
//        if ($count){
//            $this->redis->hset(Config::get('collect.count').$uuid,array_search($type,Config::get('collect')),bcsub($count,1));
//        }

        $this->result['status'] = 1;
        $this->result['msg'] = '取消收藏成功';
        return $this->result;
    }
    /**
     * CRM 我的收藏
     * @param $type
     * @param $uuid
     * @param string $keywords
     * @param int $page
     * @param int $limit
     * @return array
     * @throws
     */
    public function crmCollectList($type,$uuid,$keywords ='',$page=0,$limit=10){
        //选择表名
        $tbl = UserCollectType::$tableName .= $type;
        $model = new UserCollectType();
        $page = bcadd($page,1);
        $collect = $model->table($tbl)
            ->where('user_no',$uuid)
            ->where('status',1)
            ->order('created_at','desc');
        if ($keywords != ''){
            switch ($type) {
                case "_news":
                    $collect->where('title','like','%'.$keywords.'%');
                    break;
                case "_company":
                    $collect->where('company_name','like','%'.$keywords.'%');
                    break;
                case "_tank_organ":
                    $collect->where('company_name','like','%'.$keywords.'%');
                    break;
                case "_master":
                    $collect->where('name','like','%'.$keywords.'%');
                    break;
                case "_invest_organ":
                    $collect->where('organ_name','like','%'.$keywords.'%');
                    break;
                case "_invest_event":
                    $collect->where('event_name','like','%'.$keywords.'%');
                    break;
                case "_project":
                    $collect->where('project_name','like','%'.$keywords.'%')->field('*,');
                    break;
                default:
                    return $this->error('未知类型');
            }
        }

        $data = $collect->page($page)
            ->limit($limit)
            ->select()
            ->toArray();
        $count = $model->table($tbl)
            ->where('user_no',$uuid)
            ->where('status',1)
            ->count();

        // 需要json_decode的字段
        if (!empty($data) && in_array($type,array('_invest_event','_invest_organ'))){
            array_walk($data,array($this,'dealJsonFiled'));
        }

        $top=array();
        for ($i=1;$i<=7;$i++){
            //选择表名
            $tbl=Config::get('collect.'.$i);
            $top[$tbl]=db('user_collect_type'.$tbl)->where('status',1)->where('user_no',$uuid)->count();
        }
        $result = compact('data','count','top');
        return $this->success('success','1',$result);
    }

    /**
     * array_walk 回调处理
     * @param $value
     * @param $key
     */
    public function dealJsonFiled(&$value,$key){
        $value['industry'] = json_decode($value['industry']);
        if (isset($value['city'])){
            $value['city'] = json_decode($value['city']);
        }
    }
}